import { defineStore } from "pinia";
import { queryTree } from '@/module/org/api/dept'
import Validator from '@/utils/Validator';
const useDeptStore = defineStore('dept', () => {
    // 部门选择树
    const deptTree = ref([])
    // 部门映射
    const deptMap = ref({})
    // 获取部门选择树
    function getTree() {
        return new Promise(function (resolve, reject) {
            if (Validator.isEmpty(deptTree.value)) {
                queryTree().then(res => {
                    deptTree.value = res
                    buildDeptMap(res)
                    resolve(deptTree.value)
                })
            } else {
                resolve(deptTree.value)
            }
        })
    }
    // 更新部门选择树
    function freshTree() {
        return new Promise(function (resolve, reject) {
            queryTree().then(res => {
                deptTree.value = res
                buildDeptMap(res)
                resolve(deptTree.value)
            })
        })
    }

    function buildDeptMap(deptArr){
        deptArr.forEach((dept) => {
            let obj = deptMap.value;
            obj[dept.id] = dept.deptName;
            deptMap.value = obj;
    
            if (dept.children != null && dept.children.length > 0) {
                buildDeptMap(dept.children);
            }
            // console.log(deptMap.value);
        });
    }
    function getDeptName(deptId){
        if(Validator.isEmpty(deptMap.value)){
            return ""
        }else{
            return deptMap.value[deptId];
        }
    }
    return { deptTree, getTree, freshTree, deptMap, getDeptName }
})
export default useDeptStore